package middleware

import (
	"log"
	"net/http"
	"time"
)

// LoggingMiddleware 创建日志中间件，记录请求处理信息
func LoggingMiddleware() func(http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			// 记录开始时间
			startTime := time.Now()

			// 包装ResponseWriter以捕获状态码
			wrapped := NewResponseWriterWrapper(w)

			// 处理请求，传递包装后的ResponseWriter
			next.ServeHTTP(wrapped, r)

			// 计算处理时间
			duration := time.Since(startTime)

			// 获取状态码，如果没有设置则默认为200
			statusCode := wrapped.Status
			if statusCode == 0 {
				statusCode = http.StatusOK
			}

			// 记录请求信息
			log.Printf(
				"[%s] %s %s %d %s",
				r.Method,
				r.RequestURI,
				r.RemoteAddr,
				statusCode,
				duration,
			)
		})
	}
}
